<template>
  <div class="pdf-viewer-layout">
    <aside class="pdf-toc">
      <div class="toc-title">PDF 目录</div>
      <ul>
        <li v-for="item in outline" :key="item.id">
          <a href="#" @click.prevent="goToPage(item.pageNumber)">{{ item.title }}</a>
        </li>
      </ul>
    </aside>
    <main class="pdf-content">
      <canvas ref="canvas"></canvas>
      <!-- 预留：后续可在canvas下方渲染可复制的代码块区域 -->
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf'
import pdfjsWorker from 'pdfjs-dist/legacy/build/pdf.worker?worker&url'
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker

const route = useRoute()
const canvas = ref(null)
const outline = ref([])
let pdfDoc = null

async function loadPdf() {
  const filename = route.params.filename
  const url = `/docs/${decodeURIComponent(filename)}`
  console.log(url)
  const loadingTask = pdfjsLib.getDocument(url)
  pdfDoc = await loadingTask.promise
  // 获取大纲
  const outlineArr = await pdfDoc.getOutline()
  outline.value = (outlineArr || []).map((item, idx) => ({
    id: idx,
    title: item.title,
    pageNumber: item.dest ? item.dest[0].num : idx + 1
  }))
  renderPage(1)
}

async function renderPage(pageNum) {
  if (!pdfDoc) return
  const page = await pdfDoc.getPage(pageNum)
  const viewport = page.getViewport({ scale: 1.5 })
  const context = canvas.value.getContext('2d')
  canvas.value.height = viewport.height
  canvas.value.width = viewport.width
  await page.render({ canvasContext: context, viewport }).promise
}

function goToPage(pageNum) {
  renderPage(pageNum)
}

onMounted(loadPdf)
</script>

<style scoped>
.pdf-viewer-layout {
  display: flex;
  min-height: 100vh;
  background: #f7f8fa;
}
.pdf-toc {
  width: 220px;
  background: #fff;
  border-right: 1px solid #eee;
  padding: 24px 12px 24px 24px;
  position: sticky;
  top: 0;
  height: 100vh;
  overflow-y: auto;
}
.toc-title {
  font-weight: bold;
  font-size: 1.2rem;
  margin-bottom: 16px;
}
.pdf-toc ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
.pdf-toc li {
  margin-bottom: 8px;
}
.pdf-content {
  flex: 1;
  padding: 40px 32px;
  background: #f7f8fa;
  min-width: 0;
  overflow-x: auto;
  text-align: left;
  max-width: 900px;
  margin: 0;
}
</style>